#import "LogInOutManager.h"
#import "UserInfo.h"
#import "UserDao.h"
#import "DBManager.h"

static LogInOutManager *mgr;

@implementation LogInOutManager

+(LogInOutManager *)getInstance{
    if (mgr == nil) {
        mgr = [[LogInOutManager alloc]init];
    }
    return mgr;
}

- (BOOL)joinSchool:(NSDictionary *)dict schoolCode:(NSString*) schoolCode{
    NSDictionary *ret_dict = [[dict objectForKey:@"data"]objectAtIndex:0];
    long school_id = [[ret_dict objectForKey:@"id"] integerValue];
    NSString* school_name = [ret_dict objectForKey:@"name"];
    
    //更新数据到内存中
   // [[UserInfo getInstance] setSchoolId:school_id];
   // [[UserInfo getInstance] setSchoolName:school_name];
   // [[UserInfo getInstance] setSchoolCode:schoolCode];
    
    //更新数据到数据库
    NSMutableDictionary *db_dict = [NSMutableDictionary dictionaryWithCapacity:10];
    [db_dict setValue:schoolCode forKey:@"schoolcode"];
    [db_dict setValue:school_name forKey:@"schoolname"];
    [db_dict setValue:[ret_dict objectForKey:@"id"] forKey:@"schoolid"];
    
    NSString *limit_ = [NSString stringWithFormat:@"id = %ld", [[UserDao getInstance] getUserInfo].userId];
    [[DBManager getInstanse] updateTable:@"myinfo" updateDict:db_dict limits:limit_];
    
    return true;
}

//教师登录，重新登录，注册成功后都调用这个进行内存，数据库的初始化。
-(int)teacherLoginCallback:(NSDictionary *)dict{
    int retValue = -1;  //返回码  1-进入主界面   2-修改园长号界面  3-老师加入学校界面
    
    NSMutableDictionary *db_dict = [NSMutableDictionary dictionaryWithCapacity:10];
    
    NSDictionary *dict_myinfo = [dict objectForKey:@"myinfo"];
    
    long uid = [[dict_myinfo objectForKey:@"id"] integerValue];
    long level = [[dict_myinfo objectForKey:@"level"] integerValue];
    NSString *name = [dict_myinfo objectForKey:@"name"];
    NSString *username = [dict_myinfo objectForKey:@"username"];
    NSString *phone = [dict_myinfo objectForKey:@"phone"];
    long schoolid = [[dict_myinfo objectForKey:@"schoolid"] integerValue];
    NSString *avatar = [dict_myinfo objectForKey:@"avatar"];
    NSString *avatar_header = [dict_myinfo objectForKey:@"avatar_header"];
    long status = [[dict_myinfo objectForKey:@"status"] integerValue];
    NSString *access_token = [dict_myinfo objectForKey:@"access_token"];
    
    //[[UserInfo getInstance] setUserId:uid];
    
   // [[UserInfo getInstance] setLevel:level];
   // [[UserInfo getInstance] setNickName:name];
   // [[UserInfo getInstance] setUserName:username];
   // [[UserInfo getInstance] setPhone:phone];
   // [[UserInfo getInstance] setSchoolId:schoolid];
    //[[UserInfo getInstance] setStatus:status];
    //[[UserInfo getInstance] setAccess_token:access_token];
    
    [db_dict setValue:[NSString stringWithFormat:@"%ld", uid] forKey:@"id"];
    [db_dict setValue:[NSString stringWithFormat:@"%ld", level] forKey:@"level"];
    [db_dict setValue:[NSString stringWithFormat:@"%ld", schoolid] forKey:@"schoolid"];
    [db_dict setValue:[NSString stringWithFormat:@"%ld", status] forKey:@"status"];
    [db_dict setValue:name forKey:@"name"];
    [db_dict setValue:username forKey:@"username"];
    [db_dict setValue:phone forKey:@"phone"];
    [db_dict setValue:access_token forKey:@"access_token"];
    [db_dict setValue:@"1" forKey:@"hasLogin"];
    
    
    if ([avatar isEqual:[NSNull null]]) {
        //[[UserInfo getInstance] setAvatar:@"null"];
        [db_dict setValue:@"null" forKey:@"avatar"];
    }else{
        NSString* appendString = [avatar_header stringByAppendingString:avatar];
      //  [[UserInfo getInstance] setAvatar:appendString];
        [db_dict setValue:appendString forKey:@"avatar"];
    }
    NSString *str_whichClass = @"0";
    
    DBManager *dbMgr = [DBManager getInstanse];
    //存在班级信息，需要将数据库中的登录用户的班级信息记录删除，将服务器上最新的班级信息插入到数据库中，并更新内存。
    NSArray *arr_classinfo = [dict objectForKey:@"classinfo"];
    
    if ([arr_classinfo count] != 0) {  //服务器发送过来的数据存在最新的班级信息
        NSString *limit_ = [NSString stringWithFormat:@"userid = %ld",[[UserDao getInstance] getUserInfo].userId];
        [dbMgr deleteFrom:@"myclassinfo" limits:limit_];
        
        str_whichClass = [[arr_classinfo objectAtIndex:0]objectForKey:@"id"];
        NSMutableDictionary * temp_dict;
        NSString *str = [NSString stringWithFormat:@"%ld",[[UserDao getInstance] getUserInfo].userId];
        for (temp_dict in arr_classinfo) {
            //内存更新
          //  [[UserInfo getInstance].classInfo addObject:temp_dict];
            NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:temp_dict];
            [mDict setValue:str forKey:@"userid"];
            //插入数据到DB
            [dbMgr insertTo:@"myclassinfo" dictionary:mDict];
        }
    }
    
    if (level == 2) { //登录类型是：园长
        NSString *schoolName = [dict objectForKey:@"schoolname"];
        NSString *schoolCode = [dict objectForKey:@"schoolcode"];
       // [[UserInfo getInstance] setSchoolName:schoolName];
       // [[UserInfo getInstance] setSchoolCode:schoolCode];
        [db_dict setValue:schoolName forKey:@"schoolname"];
        [db_dict setValue:schoolCode forKey:@"schoolcode"];
        
        NSString *confirmFlag = [dict objectForKey:@"confirm"];
        [db_dict setValue:confirmFlag forKey:@"confirm"];
        
        if ([confirmFlag isEqualToString:@"1"]) { //已经修改过一次园长号，不可继续修改。直接进入主界面动态。
            retValue = 1;
        }else{  //否则进入修改园长号的界面
            retValue = 2;
        }
    }else if (level == 3){ //登录类型是：老师
        if (schoolid == 0) { //老师没有加入过任何学校的处理
            retValue = 3;
        }else{
            NSString *schoolName = [dict objectForKey:@"schoolname"];
            NSString *schoolCode = [dict objectForKey:@"schoolcode"];
          //  [[UserInfo getInstance] setSchoolName:schoolName];
           // [[UserInfo getInstance] setSchoolCode:schoolCode];
            [db_dict setValue:schoolName forKey:@"schoolname"];
            [db_dict setValue:schoolCode forKey:@"schoolcode"];
            retValue = 1;
        }
    }
    
    NSMutableArray *arr_myinfo = [dbMgr selectFrom:@"myinfo" items:[NSArray arrayWithObjects:@"whichClass",@"mycoursetype", nil] limits:[NSString stringWithFormat:@"id = %ld",[[UserDao getInstance] getUserInfo].userId]];
    
    NSString *str_myCourseType = @"1";
    if ([arr_myinfo count] != 0) { //有数据在arr_myinfo表中
        str_whichClass = [[arr_myinfo objectAtIndex:0]objectAtIndex:0];
        str_myCourseType = [[arr_myinfo objectAtIndex:0]objectAtIndex:1];
        
        //使用服务器上得数据覆盖更新本地数据，保持与服务器数据同步。
        [dbMgr updateTable:@"myinfo" updateDict:db_dict limits:[NSString stringWithFormat:@"id = %ld",[[UserDao getInstance] getUserInfo].userId]];
    }else{
        //本地个人信息表中没有数据，直接插入一条数据。
        [db_dict setValue:str_whichClass forKey:@"whichClass"];
        [db_dict setValue:str_myCourseType forKey:@"mycoursetype"];
        [dbMgr insertTo:@"myinfo" dictionary:db_dict];
    }
    
    //更新到内存
    //[UserInfo getInstance].whichClass = [str_whichClass integerValue];
  //  [UserInfo getInstance].courseType = [str_myCourseType integerValue];
    NSLog(@"retValue: %d",retValue);
    return retValue;
}

/**
 退出登录(修改数据库中的hasLogin标志位,清理当前账户的所管理的班级数组)
 */
-(BOOL)accountLogOut{
    DBManager *dbMgr = [DBManager getInstanse];
    NSDictionary *db_dict = [NSDictionary dictionaryWithObject:@"0" forKey:@"hasLogin"];
    NSString *limit_ = [NSString stringWithFormat:@"id = %ld",[[UserDao getInstance] getUserInfo].userId];
    [dbMgr updateTable:@"myinfo" updateDict:db_dict limits:limit_];
    //[[UserInfo getInstance] clearClassInfoArray];
    //跳转到登录注册界面
    return true;
}

@end
